package com.duowei.diandan.activity;

import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.duowei.diandan.BuildConfig;
import com.duowei.diandan.R;
import com.duowei.diandan.app.FrontHelper;
import com.duowei.diandan.app.InitManager;
import com.duowei.diandan.app.OrderList;
import com.duowei.diandan.bean.UserCardInfo;
import com.duowei.diandan.bean.food.Meal;
import com.duowei.diandan.bean.food.MealChildGroup;
import com.duowei.diandan.bean.food.Single;
import com.duowei.diandan.bean.food.SingleAndMeals;
import com.duowei.diandan.bean.food.SingleGroup;
import com.duowei.diandan.constant.OrderMode;
import com.duowei.diandan.constant.PlateMode;
import com.duowei.diandan.constant.QrCodeType;
import com.duowei.diandan.constant.ScanPayType;
import com.duowei.diandan.constant.Settings;
import com.duowei.diandan.event.ToastEvent;
import com.duowei.diandan.fragment.ChoiceFragment;
import com.duowei.diandan.fragment.ChoicePayFragment;
import com.duowei.diandan.fragment.CloudDetailFragment;
import com.duowei.diandan.fragment.CloudLoginFragment;
import com.duowei.diandan.fragment.DataCommitFragment;
import com.duowei.diandan.fragment.DeskFragment;
import com.duowei.diandan.fragment.InputPlateNoFragment;
import com.duowei.diandan.fragment.MealFragment;
import com.duowei.diandan.fragment.MenuFragment;
import com.duowei.diandan.fragment.OrderFragment;
import com.duowei.diandan.fragment.QrCodePay2Fragment;
import com.duowei.diandan.fragment.QrCodePayFragment;
import com.duowei.diandan.fragment.SingleAndMealFragment;
import com.duowei.diandan.fragment.SingleGroupFragment;
import com.duowei.diandan.fragment.dialog.PromptDialogFragment;
import com.duowei.diandan.impl.OnButtonGroupClickListener;
import com.duowei.diandan.viewmodel.RollMessageViewModel;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import pl.com.salsoft.sqlitestudioremote.SQLiteStudioService;

public class ContainerActivity extends BaseActivity {
    private static final String TAG = "ContainerActivity";

    private TextView mScrollingTextView;
    private FrontHelper mFrontHelper;

    private boolean mFromCloud;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_container);

        if (BuildConfig.DEBUG) {
            SQLiteStudioService.instance().start(this);
        }

        initRollMessageView();

        mFrontHelper = new FrontHelper(this);
        InitManager.getInstance().setMaxCountdownSecond(Settings.COUNTDOWN_SECOND);
        InitManager.getInstance().setCanDownTime(true);
        OrderList.getInstance().setQrCodePay(null);
        OrderList.getInstance().setPaymentList(null);

        getSupportFragmentManager().addOnBackStackChangedListener(() -> {
            int count = getSupportFragmentManager().getBackStackEntryCount();
            if (count > 0) {
                FragmentManager.BackStackEntry backStackEntry = getSupportFragmentManager()
                        .getBackStackEntryAt(count - 1);
                setScrollingTextViewVisibility(backStackEntry.getName());
            }
        });

        switch (Settings.ORDER_MODE) {
            case COMMIT:
                showDeskFragment();
                break;

            case SELF_SERVICE_MEMBER:
                showCloudLoginFragment();
                break;

            case SELF_SERVICE:
                showChoiceFragment();
                break;
        }
    }

    private void setScrollingTextViewVisibility(String fragmentTag) {
        if (Settings.ROLL_MESSAGE_ENABLED) {
            switch (fragmentTag) {
                case MenuFragment.TAG:
                case SingleGroupFragment.TAG:
                case SingleAndMealFragment.TAG:
                case MealFragment.TAG:
                case OrderFragment.TAG:
                    mScrollingTextView.setVisibility(View.VISIBLE);
                    break;

                default:
                    mScrollingTextView.setVisibility(View.GONE);
                    break;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mFrontHelper.start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mFrontHelper.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (BuildConfig.DEBUG) {
            SQLiteStudioService.instance().stop();
        }
    }

    private void initRollMessageView() {
        mScrollingTextView = findViewById(R.id.scrollingTextView);

        if (Settings.ROLL_MESSAGE_ENABLED) {
            mScrollingTextView.setVisibility(View.VISIBLE);
            mScrollingTextView.setSelected(true);
            mScrollingTextView.setBackgroundColor(Settings.ROLL_MESSAGE_BG_COLOR);
            mScrollingTextView.setTextColor(Settings.ROLL_MESSAGE_FONT_COLOR);
            mScrollingTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, Settings.ROLL_MESSAGE_FONT_SIZE);

            if (Settings.COUNTDOWN_ENABLED) {
                mScrollingTextView.setPadding(
                        mScrollingTextView.getPaddingLeft(),
                        mScrollingTextView.getPaddingTop(),
                        mScrollingTextView.getPaddingRight() + 75,
                        mScrollingTextView.getPaddingBottom()
                );
            }

            RollMessageViewModel model = ViewModelProviders.of(this)
                    .get(RollMessageViewModel.class);
            model.getLiveData().observe(this, rollMessages -> {
                //noinspection ConstantConditions
                if (rollMessages.size() == 0) {
                    mScrollingTextView.setText("未发现滚动信息设置");

                } else {
                    String text = rollMessages.get(0).getText();

                    if (TextUtils.isEmpty(text)) {
                        mScrollingTextView.setText("未发现滚动信息设置");
                    } else {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < 10; i++) {
                            sb.append(text.replace("\n", "       "))
                                    .append("       ");
                        }
                        mScrollingTextView.setText(sb.toString());
                    }
                }
            });

        } else {
            mScrollingTextView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onBackPressed() {
        // Fragment返回处理
        if (getSupportFragmentManager().getBackStackEntryCount() >= 2) {
            FragmentManager.BackStackEntry backStackEntry = getSupportFragmentManager()
                    .getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount() - 1);
            String name = backStackEntry.getName();
            if (name != null) {
                switch (name) {
                    case OrderFragment.TAG:
                    case MenuFragment.TAG:
                        if (OrderMode.COMMIT == Settings.ORDER_MODE) {
                            // 下单模式时,弹出退出提示
                            PromptDialogFragment fragment = PromptDialogFragment.newInstance(
                                    "确定退出?", false);
                            fragment.show(getSupportFragmentManager(), null);
                            fragment.setOnBtnClickListener(new PromptDialogFragment.OnBtnClickListener() {
                                @Override
                                public void onCancelBtnClick() {
                                }

                                @Override
                                public void onOkBtnClick() {
                                    getSupportFragmentManager().popBackStack(DeskFragment.TAG, 0);
                                }
                            });
                        } else {
                            super.onBackPressed();
                        }
                        break;

                    case MealFragment.TAG:
                        gotoMenuFragment();
                        break;

                    default:
                        super.onBackPressed();
                        break;
                }
            } else {
                super.onBackPressed();
            }

        } else {
            finish();
        }
    }

    private int getMainLayoutId() {
        return R.id.mainLayout;
    }

    // -----------------------------------------
    // -----------------------------------------

    // 餐桌选择
    public void showDeskFragment() {
        DeskFragment fragment = new DeskFragment();
        fragment.setOnGotoListener(new DeskFragment.OnGotoListener() {
            @Override
            public void onGotoOrderFragment() {
                showOrderFragment();
            }

            @Override
            public void onGotoMenuFragment() {
                showMenuFragment();
            }
        });

        addToBackStack(fragment, DeskFragment.TAG);
    }

    // 堂食、外带
    public void showChoiceFragment() {
        ChoiceFragment fragment = new ChoiceFragment();
        fragment.setOnClickListener(new ChoiceFragment.OnClickListener() {
            @Override
            public void gotoMenuFragment() {
                mFromCloud = false;
                showMenuFragment();
            }

            @Override
            public void gotoOrderFragment() {
                mFromCloud = false;
                showOrderFragment();
            }

            @Override
            public void onBackClick() {
                mFromCloud = false;
                onBackPressed();
            }
        });

        addToBackStack(fragment, ChoiceFragment.TAG);
    }

    // 菜单
    public void showMenuFragment() {
        MenuFragment fragment = new MenuFragment();
        fragment.setOnClickListener(new MenuFragment.OnClickListener() {

            @Override
            public void onSingleGroupClick(SingleGroup singleGroup) {
                showGroupFragment(singleGroup);
            }

            @Override
            public void onSingleOrMealGroupClick(Single single) {
                showSingleAndMealFragment(single);
            }

            @Override
            public void onSingleOrMealGroupClick(SingleAndMeals singleAndMeals) {
                showSingleAndMealFragment(singleAndMeals);
            }

            @Override
            public void onMealClick(Meal meal) {
                showMealFragment(meal);
            }

            @Override
            public void onOrderClick() {
                showOrderFragment();
            }
        });

        addToBackStack(fragment, MenuFragment.TAG);
    }

    // 单品
    public void showSingleAndMealFragment(Single single) {
        SingleAndMealFragment fragment = SingleAndMealFragment.newInstance(single);
        fragment.setOnClickListener(new SingleAndMealFragment.OnClickListener() {
            @Override
            public void onCloseClick() {
                gotoMenuFragment();
            }

            @Override
            public void onMealClick(Meal meal) {
                showMealFragment(meal);
            }
        });

        addToBackStack(fragment, SingleAndMealFragment.TAG);
    }

    // 单品、套餐
    public void showSingleAndMealFragment(SingleAndMeals singleAndMeals) {
        SingleAndMealFragment fragment = SingleAndMealFragment.newInstance(singleAndMeals);
        fragment.setOnClickListener(new SingleAndMealFragment.OnClickListener() {
            @Override
            public void onCloseClick() {
                gotoMenuFragment();
            }

            @Override
            public void onMealClick(Meal meal) {
                showMealFragment(meal);
            }
        });

        addToBackStack(fragment, SingleAndMealFragment.TAG);
    }

    // 套餐
    public void showMealFragment(Meal meal) {
        List<MealChildGroup> mealChildGroupList = meal.getMealChildGroupList();
        if (mealChildGroupList == null || mealChildGroupList.size() == 0) {
            // 没有套餐子项
            EventBus.getDefault().post(new ToastEvent(meal.getMainTcsd().getXmmc1() + "+1", true));
            OrderList.getInstance().addMeal(meal.getMainTcsd());

        } else {
            MealFragment fragment = MealFragment.newInstance(meal);
            fragment.setOnClickListener(this::gotoMenuFragment);

            addToBackStack(fragment, MealFragment.TAG);
        }
    }

    // 单品组
    public void showGroupFragment(SingleGroup singleGroup) {
        SingleGroupFragment fragment = SingleGroupFragment.newInstance(singleGroup);
        fragment.setOnClickListener(new SingleGroupFragment.OnClickListener() {

            @Override
            public void onHasPresentOrAddPrice(Single single) {
                showSingleAndMealFragment(single);
            }

            @Override
            public void onSingleAndMeals(SingleAndMeals singleAndMeals) {
                showSingleAndMealFragment(singleAndMeals);
            }

            @Override
            public void onCloseClick() {
                gotoMenuFragment();
            }
        });

        addToBackStack(fragment, SingleGroupFragment.TAG);
    }

    // 购物车
    public void showOrderFragment() {
        OrderFragment fragment = OrderFragment.newInstance(mFromCloud);
        fragment.setOnClickListener(new OrderFragment.OnClickListener() {

            @Override
            public void onPayOrderClick() {
                if (mFromCloud) {
                    getSupportFragmentManager().popBackStack(CloudDetailFragment.TAG, 0);

                } else {
                    if (PlateMode.HAND == Settings.PLATE_MODE) {
                        showInputPlateNoFragment();
                    } else {
                        if (OrderMode.SELF_SERVICE_MEMBER == Settings.ORDER_MODE) {
                            showCloudDetailFragment(Settings.USER_CARD_INFO);

                        } else {
                            showChoicePayFragment();
                        }
                    }
                }
            }

            @Override
            public void gotoMenuFragment() {
                if (mFromCloud) {
                    showMenuFragment();

                } else {
                    ContainerActivity.this.gotoMenuFragment();
                }

            }

            @Override
            public void onBackClick() {
                getSupportFragmentManager().popBackStack(ChoiceFragment.TAG, 0);
            }
        });

        addToBackStack(fragment, OrderFragment.TAG);
    }

    // 输入餐牌号
    public void showInputPlateNoFragment() {
        InputPlateNoFragment fragment = new InputPlateNoFragment();
        fragment.setOnButtonGroupClickListener(new OnButtonGroupClickListener() {
            @Override
            public void onLeftButtonClick() {
                onBackPressed();
            }

            @Override
            public void onRightButtonClick() {
                if (OrderMode.SELF_SERVICE_MEMBER == Settings.ORDER_MODE) {
                    showCloudDetailFragment(Settings.USER_CARD_INFO);

                } else {
                    showChoicePayFragment();
                }
            }
        });

        addToBackStack(fragment, InputPlateNoFragment.TAG);
    }

    // 选择付款方式
    public void showChoicePayFragment() {
        ChoicePayFragment fragment;
        if (Settings.DISTINGUISH_BETWEEN_MEMBERS) {
            fragment = ChoicePayFragment.newInstance(ChoicePayFragment.TYPE_NUMBERS);
        } else {
            fragment = ChoicePayFragment.newInstance(ChoicePayFragment.TYPE_FOUR);
        }

        fragment.setOnButtonClickListener(new ChoicePayFragment.OnButtonClickListener() {
            @Override
            public void onBackButtonClick() {
                onBackPressed();
            }

            @Override
            public void onWeixinClick() {
                showQrCodePayFragment(false, QrCodeType.WECHATPAY,
                        OrderList.getInstance().getMoney().getReceivableFloat());
            }

            @Override
            public void onAlipayClick() {
                showQrCodePayFragment(false, QrCodeType.ALIPAY,
                        OrderList.getInstance().getMoney().getReceivableFloat());
            }

            @Override
            public void onNoCloudClick() {
                showChoice2PayFragment();
            }

            @Override
            public void onCloudClick() {
                showCloudLoginFragment();
            }

//            @Override
//            public void onCommitClick() {
//                showDataCommitFragment(false);
//            }
        });

        addToBackStack(fragment, ChoicePayFragment.TAG);
    }

    public void showChoice2PayFragment() {
        ChoicePayFragment fragment = ChoicePayFragment.newInstance(ChoicePayFragment.TYPE_QR_CODE);
        fragment.setOnButtonClickListener(new ChoicePayFragment.OnButtonClickListener() {
            @Override
            public void onBackButtonClick() {
                onBackPressed();
            }

            @Override
            public void onWeixinClick() {
                showQrCodePayFragment(false, QrCodeType.WECHATPAY,
                        OrderList.getInstance().getMoney().getReceivableFloat());
            }

            @Override
            public void onAlipayClick() {
                showQrCodePayFragment(false, QrCodeType.ALIPAY,
                        OrderList.getInstance().getMoney().getReceivableFloat());
            }

            @Override
            public void onNoCloudClick() {
            }

            @Override
            public void onCloudClick() {
            }

        });

        addToBackStack(fragment, ChoicePayFragment.TAG);
    }

    // 二维码支付
    public void showQrCodePayFragment(boolean isCloudQrCode, QrCodeType type, float payMoney) {
        OrderList.getInstance().setCloudQrCode(isCloudQrCode);

        if (ScanPayType.SELF_TYPE == Settings.SCAN_PAY_TYPE) {
            QrCodePayFragment fragment = QrCodePayFragment.newInstance(type, payMoney);
            fragment.setOnStatusListener(new QrCodePayFragment.OnStatusListener() {
                @Override
                public void onCloseClick() {
                    onBackPressed();
                }

                @Override
                public void onPaySuccess() {
                    showDataCommitFragment(true);
                }
            });

            addToBackStack(fragment, QrCodePayFragment.TAG);

        } else {
            QrCodePay2Fragment fragment = QrCodePay2Fragment.newInstance(type, payMoney);
            fragment.setOnStatusListener(new QrCodePay2Fragment.OnStatusListener() {
                @Override
                public void onCloseClick() {
                    onBackPressed();
                }

                @Override
                public void onPaySuccess() {
                    showDataCommitFragment(true);
                }
            });

            addToBackStack(fragment, QrCodePay2Fragment.TAG);
        }
    }

    // 云会员登录
    public void showCloudLoginFragment() {
        CloudLoginFragment fragment = new CloudLoginFragment();
        fragment.setOnClickListener(new CloudLoginFragment.OnClickListener() {
            @Override
            public void onBackClick() {
                onBackPressed();
            }

            @Override
            public void onLoginClick() {
                fragment.setLanding(true);
            }

            @Override
            public void onLoginMessage(String message) {
                fragment.setLanding(false);
                EventBus.getDefault().post(new ToastEvent(message, false));
            }

            @Override
            public void onLoginSuccess(UserCardInfo userCardInfo) {
                Settings.USER_CARD_INFO = userCardInfo;

                fragment.setLanding(false);
                showCloudDetailFragment(userCardInfo);
            }

            @Override
            public void onMemberModeClick(UserCardInfo userCardInfo) {
                Settings.USER_CARD_INFO = userCardInfo;

                showChoiceFragment();
            }
        });

        addToBackStack(fragment, CloudLoginFragment.TAG);
    }

    // 云会员详情
    public void showCloudDetailFragment(UserCardInfo userCardInfo) {
        CloudDetailFragment fragment = CloudDetailFragment.newInstance(userCardInfo);
        fragment.setOnButtonClickListener(new CloudDetailFragment.OnButtonClickListener() {

            @Override
            public void onWeixinPayClick(float payMoney) {
                showQrCodePayFragment(true, QrCodeType.WECHATPAY, payMoney);
            }

            @Override
            public void onAlipayClick(float payMoney) {
                showQrCodePayFragment(true, QrCodeType.ALIPAY, payMoney);
            }

            @Override
            public void onLogoutClick() {
                mFromCloud = false;

                if (Settings.ORDER_MODE == OrderMode.SELF_SERVICE) {
                    // 快餐模式不返回到登陆界面，直接返回到付款方式选择界面
                    getSupportFragmentManager().popBackStack(ChoicePayFragment.TAG, 0);

                } else {
                    onBackPressed();
                }
            }

            @Override
            public void onConfirmPayClick() {
                showDataCommitFragment(true);
            }

            @Override
            public void onBackCartClick() {
                mFromCloud = true;

                showOrderFragment();
            }
        });

        addToBackStack(fragment, CloudDetailFragment.TAG);
    }

    // 提交数据
    public void showDataCommitFragment(boolean remoteCommit) {
        DataCommitFragment fragment = DataCommitFragment.newInstance(remoteCommit);

        addToBackStack(fragment, DataCommitFragment.TAG);
    }

    private void addToBackStack(Fragment fragment, String name) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out,
                android.R.anim.fade_in, android.R.anim.fade_out);
        ft.replace(getMainLayoutId(), fragment)
                .addToBackStack(name)
                .commit();

    }

    private void gotoMenuFragment() {
        int count = getSupportFragmentManager().getBackStackEntryCount();
        boolean findMenuFragment = false;
        for (int i = 0; i < count; i++) {
            FragmentManager.BackStackEntry backStackEntry = getSupportFragmentManager().getBackStackEntryAt(i);
            if (MenuFragment.TAG.equals(backStackEntry.getName())) {
                findMenuFragment = true;
                break;
            }
        }

        if (findMenuFragment) {
            getSupportFragmentManager().popBackStack(MenuFragment.TAG, 0);
        } else {
            showMenuFragment();
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        return super.dispatchKeyEvent(event);
    }
}
